#!/usr/bin/python
# -*- coding: utf-8 -*-
# 抖音去水印工具（修复版）

import json
import requests
import re
import urllib3
from bs4 import BeautifulSoup


urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def get_video_id(short_url):
    """获取视频ID"""
    try:
        res = requests.get(short_url,
                           headers={
                               'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'},
                           allow_redirects=False,
                           verify=False,
                           timeout=10)

        if res.status_code == 302:
            redirect_url = res.headers['Location']
            # 新版链接格式处理
            if '/video/' in redirect_url:
                return re.search(r'/video/(\d+)', redirect_url).group(1)
            # 兼容旧版链接格式
            return re.search(r'item_ids=(\d+)', redirect_url).group(1)

        raise Exception(f"获取失败，状态码：{res.status_code}")
    except Exception as e:
        print("获取视频ID失败:", str(e))
        return None


def get_video_info(item_id):
    """获取视频信息"""
    api_url = f"https://www.iesdouyin.com/share/video/{item_id}"

    headers = {
        'Referer': 'https://www.douyin.com/',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
    }



    try:
        response = requests.get(api_url, headers=headers, verify=False, timeout=10)
        if response.status_code != 200:
            return None

        res = response.text
        title = re.findall('<title[^>]*>(.*?)</title>', res)[0]
        print("title", title)

        data = re.findall('_ROUTER_DATA\s*=\s*({.*?});',res)[0]
        info = json.loads(data)
        # url = info['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['video']['play_addr']['url_list'][0]
        # if data.get('status_code') != 0:
        #     return None

        return info
    except Exception as e:
        print("获取视频信息失败:", str(e))
        return None


def download_video(url, filename):
    """下载视频"""

    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'}
        response = requests.get(url, headers=headers, stream=True, verify=False, timeout=20)

        with open(f"{filename}.mp4", 'wb') as f:
            for chunk in response.iter_content(chunk_size=1024 * 1024):
                if chunk:
                    f.write(chunk)
        return True
    except Exception as e:
        print("下载失败:", str(e))
        return False


if __name__ == "__main__":
    print("===> 抖音去水印工具（修复版）")
    input_url = input("===> 请输入抖音分享链接：").strip()

    # 提取短链接ID
    short_id = re.search(r'douyin\.com/(\w+)', input_url).group(1)
    if not short_id:
        print("链接格式错误！")
        exit()

    # 获取视频ID
    item_id = get_video_id(f"https://v.douyin.com/{short_id}")
    if not item_id:
        print("无法获取视频ID，请检查链接有效性")
        exit()

    # 获取视频信息
    video_info = get_video_info(item_id)
    if not video_info:
        print("视频信息获取失败，可能链接已失效")
        exit()

    # 提取视频地址
    video_url = video_info['loaderData']['video_(id)/page']['videoInfoRes']['item_list'][0]['video']['play_addr']['url_list'][0]

    video_url = video_url.replace('playwm', 'play')
    desc = '123tt'
    print(f"===> 开始下载：{desc}")
    if download_video(video_url, desc):
        print("===> 下载完成！")
    else:
        print("===> 下载失败！")